from rest_framework.response import Response
from rest_framework.views import APIView
# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os
from myapp.models import *
import cv2
# 序列器
from myapp.myser import *
import upyun


class UploadP(APIView):
    def post(self, request):
        # 接受参数
        myfile = request.FILES.get('file')
        print(myfile)
        myfilename = myfile.name.replace('"', '')
        # 建立文件流对象
        f = open(os.path.join(UPLOAD_ROOT, '', myfilename), 'wb')
        # 写入
        for chunk in myfile.chunks():
            f.write(chunk)
        f.close()
        # 取图
        img = Image.open('./static/upload/' + myfilename)
        # 获取宽高
        width, height = img.size
        # 添加字体
        text = 'django2.0.4'
        # 使用画笔
        draw = ImageDraw.Draw(img)
        # 写入文本 参数（（x,y），水印文字，颜色，字体）
        draw.text((width - 100, height - 50), text, fill=(76, 234, 124, 180))
        # 根据路径保存文件
        img.save(os.path.join(UPLOAD_ROOT, '', myfilename))
        # 读图
        img = cv2.imread('./static/upload/%s' % myfilename)
        # jpg压缩等级清晰0-100模糊
        cv2.imwrite('./static/upload/%s' % myfilename, img, [cv2.IMWRITE_JPEG_QUALITY, 50])
        return Response({'filename': myfile.name})


class YPPu(APIView):
    def post(self, request):
        # 获取文件
        file = request.FILES.get('file')
        print(1111111111111)
        print(file)

        return Response({'filename': file.name})


class WeekGoodlist(APIView):
    def get(self, request):
        page = request.GET.get('page', 1)
        size = request.GET.get('size', 1)
        # 从哪里开始切
        data_start = (int(page) - 1) * int(size)
        # # 切到哪里
        data_end = int(page) * int(size)
        # 切片
        goods = Goods.objects.all()[data_start:data_end]
        # 切片

        # 查询所有商品个数
        count = Goods.objects.count()
        # 序列化给前端
        goodsser = GoodsSer(goods, many=True)
        return Response({'msg': goodsser.data,'count':count})

class WeekGood(APIView):
    def get(self, request):
        id =request.GET.get('id')
        print(id)
        # 查询所有商品
        good=Goods.objects.get(id=id)
        goodser=GoodsSer(good).data

        return Response({'msg':goodser})
